/**
 * 审计服务
 * EndoSight-UC 医疗AI系统
 *
 * 提供完整的审计追踪和合规管理功能
 */

import crypto from 'crypto';
import structuredLogger, { AuditEventType, PHIDataType, generateCorrelationId } from '../utils/structuredLogger.js';
import db from '../config/database.js';

// 审计服务配置
const AUDIT_CONFIG = {
  // 数据保留策略（天）
  RETENTION_PERIODS: {
    USER_SESSIONS: 90,           // 用户会话：3个月
    MEDICAL_ACCESS: 2555,        // 医疗数据访问：7年
    AI_INFERENCE: 2555,          // AI推理：7年
    FILE_OPERATIONS: 2555,       // 文件操作：7年
    COMPLIANCE_VIOLATIONS: -1,   // 合规违规：永久保存
    SYSTEM_CONFIG: 1825,         // 系统配置：5年
    DATA_EXPORTS: 365,           // 数据导出：1年
    AUDIT_LOGS: 2555             // 审计日志：7年
  },

  // 自动清理间隔（小时）
  CLEANUP_INTERVAL: 24,

  // 批量操作大小
  BATCH_SIZE: 1000,

  // 合规检查阈值
  COMPLIANCE_THRESHOLDS: {
    PHI_ACCESS_PER_HOUR: 50,     // 每小时PHI访问次数阈值
    EXPORT_PER_DAY: 10,          // 每日导出次数阈值
    FAILED_AUTH_PER_MINUTE: 5,   // 每分钟认证失败次数阈值
    UNAUTHORIZED_ACCESS_PER_HOUR: 3 // 每小时未授权访问次数阈值
  }
};

/**
 * 审计服务类
 */
class AuditService {
  constructor() {
    this.isInitialized = false;
    this.cleanupInterval = null;
  }

  /**
   * 初始化审计服务
   */
  async initialize() {
    try {
      // 导入并初始化审计表结构
      const { initializeAuditTables, createCleanupProcedures } = await import('../config/auditSchema.js');

      await initializeAuditTables(db);
      await db.execute(createCleanupProcedures);

      this.isInitialized = true;
      structuredLogger.info('审计服务初始化成功');

      // 启动自动清理任务
      this.startCleanupTasks();

      return { success: true, message: '审计服务初始化完成' };
    } catch (error) {
      structuredLogger.error('审计服务初始化失败', error);
      throw error;
    }
  }

  /**
   * 记录用户登录
   */
  async logUserLogin(userId, loginMethod, ip, userAgent, success = true, additionalData = {}) {
    const sessionId = generateCorrelationId();
    const timestamp = new Date().toISOString();

    try {
      // 记录审计日志
      structuredLogger.audit(
        success ? AuditEventType.USER_LOGIN : AuditEventType.AUTH_FAILURE,
        success ? `用户登录成功: ${userId}` : `用户登录失败: ${userId}`,
        { type: 'user_session', id: sessionId },
        userId,
        {
          request: { ip, userAgent },
          metadata: {
            loginMethod,
            success,
            timestamp,
            ...additionalData
          }
        }
      );

      if (success) {
        // 创建用户会话记录
        await db.execute(`
          INSERT INTO user_sessions (
            id, user_id, login_time, last_activity, ip_address, user_agent,
            login_method, session_status, security_flags, session_data
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `, [
          sessionId,
          userId,
          timestamp,
          timestamp,
          ip,
          userAgent,
          loginMethod,
          'active',
          JSON.stringify({
            loginTime: timestamp,
            deviceInfo: this.extractDeviceInfo(userAgent),
            location: additionalData.location
          }),
          JSON.stringify(additionalData.sessionData || {})
        ]);

        // 记录主要审计日志
        await this.insertAuditLog({
          level: 'audit',
          message: `用户登录: ${userId}`,
          userId,
          sessionId,
          action: 'user_login',
          resourceType: 'user_session',
          resourceId: sessionId,
          ipAddress: ip,
          userAgent,
          logData: JSON.stringify({
            loginMethod,
            success,
            timestamp,
            ...additionalData
          }),
          complianceFlags: JSON.stringify({
            authEvent: true,
            sessionCreated: true
          })
        });
      }

      return { success: true, sessionId };
    } catch (error) {
      structuredLogger.error('用户登录审计记录失败', error, { userId, success });
      throw error;
    }
  }

  /**
   * 记录用户登出
   */
  async logUserLogout(userId, sessionId, logoutReason = 'user_initiated') {
    const timestamp = new Date().toISOString();

    try {
      // 更新用户会话
      await db.execute(`
        UPDATE user_sessions
        SET logout_time = ?, session_status = ?, last_activity = ?
        WHERE id = ? AND user_id = ?
      `, [timestamp, logoutReason === 'expired' ? 'expired' : 'terminated', timestamp, sessionId, userId]);

      // 记录审计日志
      structuredLogger.audit(
        AuditEventType.USER_LOGOUT,
        `用户登出: ${userId}`,
        { type: 'user_session', id: sessionId },
        userId,
        {
          metadata: {
            logoutReason,
            timestamp
          }
        }
      );

      await this.insertAuditLog({
        level: 'audit',
        message: `用户登出: ${userId}`,
        userId,
        sessionId,
        action: 'user_logout',
        resourceType: 'user_session',
        resourceId: sessionId,
        logData: JSON.stringify({
          logoutReason,
          timestamp
        })
      });

      return { success: true };
    } catch (error) {
      structuredLogger.error('用户登出审计记录失败', error, { userId, sessionId });
      throw error;
    }
  }

  /**
   * 记录医疗数据访问
   */
  async logMedicalDataAccess(userId, sessionId, patientId, dataType, accessType, reason, additionalData = {}) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      // 检测PHI字段
      const phiFields = this.detectPHIFields(additionalData.data || {});

      // 记录医疗数据访问日志
      await db.execute(`
        INSERT INTO medical_data_access_logs (
          id, audit_log_id, timestamp, user_id, session_id, patient_id,
          data_type, access_type, access_reason, consent_verified,
          consent_type, phi_present, phi_fields, data_before, data_after,
          access_granted, retention_required, retention_until
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        auditId,
        auditId,
        timestamp,
        userId,
        sessionId,
        patientId,
        dataType,
        accessType,
        reason,
        additionalData.consentVerified || false,
        additionalData.consentType || 'treatment',
        phiFields.length > 0,
        JSON.stringify(phiFields),
        JSON.stringify(additionalData.dataBefore),
        JSON.stringify(additionalData.dataAfter),
        additionalData.accessGranted !== false,
        true,
        new Date(Date.now() + (AUDIT_CONFIG.RETENTION_PERIODS.MEDICAL_ACCESS * 24 * 60 * 60 * 1000))
      ]);

      // 记录结构化日志
      structuredLogger.medicalDataAccess(userId, patientId, dataType, accessType, reason, {
        consentVerified: additionalData.consentVerified,
        consentType: additionalData.consentType,
        phiFields,
        timestamp,
        auditId
      });

      // 检查合规性
      await this.checkMedicalAccessCompliance(userId, patientId, accessType, additionalData);

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('医疗数据访问审计记录失败', error, { userId, patientId, dataType });
      throw error;
    }
  }

  /**
   * 记录AI推理审计
   */
  async logAIInference(userId, sessionId, patientId, taskId, inferenceData) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      const {
        modelVersion,
        modelName,
        inputHash,
        outputHash,
        inferenceType,
        confidenceScore,
        processingTime,
        inputSize,
        outputSize,
        status,
        errorMessage,
        clinicalDecision,
        reviewRequired
      } = inferenceData;

      // 记录AI推理审计
      await db.execute(`
        INSERT INTO ai_inference_audit (
          id, audit_log_id, timestamp, user_id, session_id, patient_id, task_id,
          model_version, model_name, input_data_hash, output_data_hash,
          inference_type, confidence_score, processing_time_ms, input_size_bytes,
          output_size_bytes, inference_status, error_message, clinical_decision,
          review_required, model_config, input_metadata, output_metadata, compliance_flags
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        auditId,
        auditId,
        timestamp,
        userId,
        sessionId,
        patientId,
        taskId,
        modelVersion,
        modelName,
        inputHash,
        outputHash,
        inferenceType,
        confidenceScore,
        processingTime,
        inputSize,
        outputSize,
        status,
        errorMessage,
        clinicalDecision || false,
        reviewRequired || false,
        JSON.stringify(inferenceData.modelConfig || {}),
        JSON.stringify(inferenceData.inputMetadata || {}),
        JSON.stringify(inferenceData.outputMetadata || {}),
        JSON.stringify({
          aiInference: true,
          clinicalDecision: clinicalDecision || false,
          modelVersion,
          timestamp
        })
      ]);

      // 记录结构化日志
      structuredLogger.aiInference(
        status === 'success' ? 'ai_inference_success' : 'ai_inference_failure',
        `AI推理${status === 'success' ? '成功' : '失败'}: ${modelName} v${modelVersion}`,
        {
          modelVersion,
          confidence: confidenceScore,
          processingTime,
          inputHash,
          outputHash,
          taskId,
          patientId
        },
        {
          userId,
          sessionId,
          auditId,
          clinicalDecision,
          reviewRequired
        }
      );

      // 如果是临床决策，记录特殊审计
      if (clinicalDecision) {
        await this.logClinicalDecision(userId, sessionId, patientId, taskId, inferenceData);
      }

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('AI推理审计记录失败', error, { userId, taskId });
      throw error;
    }
  }

  /**
   * 记录文件操作审计
   */
  async logFileOperation(userId, sessionId, operationType, fileData, additionalData = {}) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      const {
        fileName,
        filePath,
        fileType,
        fileSize,
        fileHash,
        mimeType,
        medicalImage = false,
        patientId,
        taskId,
        validationResult,
        storageLocation
      } = fileData;

      // 记录文件操作审计
      await db.execute(`
        INSERT INTO file_operation_audit (
          id, audit_log_id, timestamp, user_id, session_id, operation_type,
          file_name, file_path, file_type, file_size_bytes, file_hash, mime_type,
          medical_image, patient_id, task_id, upload_result, validation_result,
          storage_location, access_granted, retention_required, retention_until, gdpr_data
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        auditId,
        auditId,
        timestamp,
        userId,
        sessionId,
        operationType,
        fileName,
        filePath,
        fileType,
        fileSize,
        fileHash,
        mimeType,
        medicalImage,
        patientId,
        taskId,
        JSON.stringify(additionalData.uploadResult || {}),
        JSON.stringify(validationResult || {}),
        storageLocation,
        additionalData.accessGranted !== false,
        true,
        new Date(Date.now() + (AUDIT_CONFIG.RETENTION_PERIODS.FILE_OPERATIONS * 24 * 60 * 60 * 1000)),
        additionalData.gdprData || false
      ]);

      // 记录结构化日志
      structuredLogger.audit(
        `file_${operationType}`,
        `文件${operationType === 'upload' ? '上传' : operationType === 'delete' ? '删除' : operationType}: ${fileName}`,
        {
          type: 'file',
          id: auditId,
          fileName,
          fileType,
          medicalImage
        },
        userId,
        {
          metadata: {
            operationType,
            fileSize,
            medicalImage,
            patientId,
            timestamp,
            auditId
          }
        }
      );

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('文件操作审计记录失败', error, { userId, operationType });
      throw error;
    }
  }

  /**
   * 记录合规违规
   */
  async logComplianceViolation(userId, violationType, severity, description, additionalData = {}) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      const {
        regulation = 'HIPAA',
        regulationSection,
        patientId,
        dataAffected,
        remediationRequired = true,
        remediationDueDate
      } = additionalData;

      // 记录合规违规
      await db.execute(`
        INSERT INTO compliance_violations (
          id, audit_log_id, timestamp, violation_type, severity, regulation,
          regulation_section, description, user_id, patient_id, data_affected,
          remediation_required, remediation_due_date, reported_to_authorities,
          investigation_status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        auditId,
        auditId,
        timestamp,
        violationType,
        severity,
        regulation,
        regulationSection,
        description,
        userId,
        patientId,
        JSON.stringify(dataAffected || {}),
        remediationRequired,
        remediationDueDate,
        additionalData.reportedToAuthorities || false,
        'not_started'
      ]);

      // 记录结构化日志
      structuredLogger.compliance(
        'compliance_violation',
        `合规违规: ${violationType} - ${description}`,
        {
          regulation,
          section: regulationSection,
          severity,
          verified: false
        },
        {
          userId,
          patientId,
          violationType,
          severity,
          auditId,
          timestamp
        }
      );

      // 发送安全告警
      if (severity === 'high' || severity === 'critical') {
        structuredLogger.security(
          'compliance_violation',
          `严重合规违规: ${violationType}`,
          severity,
          {
            userId,
            violationType,
            description,
            requiresAction: true,
            auditId
          }
        );
      }

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('合规违规记录失败', error, { userId, violationType });
      throw error;
    }
  }

  /**
   * 记录数据导出审计
   */
  async logDataExport(userId, sessionId, exportData, additionalData = {}) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      const {
        exportType,
        exportFormat,
        dataScope,
        recordCount,
        fileSize,
        exportFilePath,
        exportFileHash,
        includesPhi,
        phiCount,
        consentVerified,
        purpose,
        recipientInfo,
        approved,
        approvedBy,
        autoDelete = true,
        deleteAfterDays = 30
      } = exportData;

      // 记录数据导出审计
      await db.execute(`
        INSERT INTO data_export_audit (
          id, audit_log_id, timestamp, user_id, session_id, export_type,
          export_format, data_scope, record_count, file_size_bytes, export_file_path,
          export_file_hash, includes_phi, phi_count, consent_verified, purpose,
          recipient_info, approved, approved_by, auto_delete, delete_after_days
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        auditId,
        auditId,
        timestamp,
        userId,
        sessionId,
        exportType,
        exportFormat,
        JSON.stringify(dataScope),
        recordCount,
        fileSize,
        exportFilePath,
        exportFileHash,
        includesPhi,
        phiCount,
        consentVerified,
        purpose,
        recipientInfo,
        approved,
        approvedBy,
        autoDelete,
        deleteAfterDays
      ]);

      // 记录结构化日志
      structuredLogger.audit(
        'data_export',
        `数据导出: ${exportType} - ${recordCount}条记录`,
        {
          type: 'data_export',
          id: auditId,
          exportType,
          includesPhi
        },
        userId,
        {
          compliance: {
            dataExport: true,
            phiPresent: includesPhi,
            consentVerified,
            approved,
            gdprRelevant: true
          },
          metadata: {
            exportFormat,
            recordCount,
            fileSize,
            purpose,
            auditId,
            timestamp
          }
        }
      );

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('数据导出审计记录失败', error, { userId, exportType });
      throw error;
    }
  }

  /**
   * 记录临床决策
   */
  async logClinicalDecision(userId, sessionId, patientId, taskId, inferenceData) {
    const timestamp = new Date().toISOString();
    const auditId = generateCorrelationId();

    try {
      // 记录特殊临床决策审计
      await this.insertAuditLog({
        level: 'compliance',
        message: `临床决策AI推理: ${inferenceData.modelName}`,
        userId,
        sessionId,
        action: 'clinical_ai_decision',
        resourceType: 'ai_inference',
        resourceId: auditId,
        logData: JSON.stringify({
          clinicalDecision: true,
          patientId,
          taskId,
          modelVersion: inferenceData.modelVersion,
          confidence: inferenceData.confidenceScore,
          timestamp
        }),
        complianceFlags: JSON.stringify({
          clinicalDecision: true,
          patientDataInvolved: true,
          reviewRequired: true,
          timestamp
        })
      });

      structuredLogger.compliance(
        'clinical_decision',
        `临床决策AI推理: 患者 ${patientId}`,
        {
          regulation: 'HIPAA',
          section: 'Clinical Decision Support',
          verified: false
        },
        {
          userId,
          patientId,
          taskId,
          auditId,
          clinicalDecision: true
        }
      );

      return { success: true, auditId };
    } catch (error) {
      structuredLogger.error('临床决策审计记录失败', error, { userId, patientId });
      throw error;
    }
  }

  /**
   * 插入审计日志
   */
  async insertAuditLog(auditData) {
    const {
      level,
      message,
      correlationId,
      userId,
      sessionId,
      action,
      resourceType,
      resourceId,
      ipAddress,
      userAgent,
      logData,
      complianceFlags,
      securityFlags
    } = auditData;

    try {
      const id = correlationId || generateCorrelationId();
      const timestamp = new Date().toISOString();

      // 计算校验和
      const checksum = this.calculateAuditChecksum({
        id,
        timestamp,
        level,
        message,
        userId,
        action,
        resourceType,
        resourceId
      });

      await db.execute(`
        INSERT INTO audit_logs (
          id, timestamp, level, correlation_id, user_id, session_id, message,
          action, resource_type, resource_id, ip_address, user_agent,
          log_data, compliance_flags, security_flags, checksum
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        id,
        timestamp,
        level,
        correlationId,
        userId,
        sessionId,
        message,
        action,
        resourceType,
        resourceId,
        ipAddress,
        userAgent,
        logData,
        complianceFlags,
        securityFlags,
        checksum
      ]);

      return id;
    } catch (error) {
      structuredLogger.error('审计日志插入失败', error);
      throw error;
    }
  }

  /**
   * 检查医疗访问合规性
   */
  async checkMedicalAccessCompliance(userId, patientId, accessType, additionalData) {
    try {
      // 检查访问频率
      const recentAccess = await db.execute(`
        SELECT COUNT(*) as count FROM medical_data_access_logs
        WHERE user_id = ? AND patient_id = ?
        AND timestamp > datetime('now', '-1 hour')
      `, [userId, patientId]);

      const accessCount = recentAccess.rows[0]?.count || 0;

      if (accessCount > AUDIT_CONFIG.COMPLIANCE_THRESHOLDS.PHI_ACCESS_PER_HOUR) {
        await this.logComplianceViolation(userId, 'excessive_phi_access', 'medium',
          `用户在1小时内访问患者数据${accessCount}次，超过阈值`, {
            patientId,
            accessType,
            accessCount,
            threshold: AUDIT_CONFIG.COMPLIANCE_THRESHOLDS.PHI_ACCESS_PER_HOUR
          });
      }

      // 检查同意状态
      if (!additionalData.consentVerified && accessType !== 'view') {
        await this.logComplianceViolation(userId, 'access_without_consent', 'high',
          `未经同意访问患者数据进行${accessType}操作`, {
            patientId,
            accessType,
            consentVerified: false
          });
      }

      return { compliant: true, warnings: [] };
    } catch (error) {
      structuredLogger.error('医疗访问合规性检查失败', error);
      return { compliant: false, error: error.message };
    }
  }

  /**
   * 计算审计校验和
   */
  calculateAuditChecksum(data) {
    const dataString = JSON.stringify(data);
    return crypto.createHash('sha256').update(dataString).digest('hex');
  }

  /**
   * 检测PHI字段
   */
  detectPHIFields(data) {
    const phiFields = [];

    // 检查常见的PHI字段名
    const phiPatterns = {
      patientName: /name|patient_name/i,
      patientId: /patient_id|mrn|medical_record/i,
      diagnosis: /diagnosis|icd/i,
      treatment: /treatment|therapy|medication/i,
      ssn: /ssn|social_security/i,
      phone: /phone|telephone/i,
      email: /email/i,
      address: /address|location/i,
      dob: /dob|date_of_birth|birth_date/i
    };

    Object.keys(data).forEach(field => {
      Object.entries(phiPatterns).forEach(([phiType, pattern]) => {
        if (pattern.test(field)) {
          phiFields.push({
            fieldName: field,
            phiType,
            hasValue: !!data[field]
          });
        }
      });
    });

    return phiFields;
  }

  /**
   * 提取设备信息
   */
  extractDeviceInfo(userAgent) {
    try {
      // 简单的User-Agent解析
      const browserMatch = userAgent.match(/(Chrome|Firefox|Safari|Edge|Opera)\/?([\d.]+)/i);
      const osMatch = userAgent.match(/\(([^)]+)\)/);

      return {
        browser: browserMatch ? `${browserMatch[1]} ${browserMatch[2]}` : 'Unknown',
        os: osMatch ? osMatch[1] : 'Unknown',
        raw: userAgent
      };
    } catch (error) {
      return { browser: 'Unknown', os: 'Unknown', raw: userAgent };
    }
  }

  /**
   * 启动自动清理任务
   */
  startCleanupTasks() {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
    }

    this.cleanupInterval = setInterval(async () => {
      await this.performCleanupTasks();
    }, AUDIT_CONFIG.CLEANUP_INTERVAL * 60 * 60 * 1000); // 转换为毫秒

    structuredLogger.info('审计数据自动清理任务已启动');
  }

  /**
   * 执行清理任务
   */
  async performCleanupTasks() {
    try {
      structuredLogger.info('开始执行审计数据清理任务');

      // 清理过期的用户会话
      await this.cleanupExpiredSessions();

      // 清理过期的数据导出
      await this.cleanupExpiredExports();

      // 清理过期的文件操作记录（除非标记为需要保留）
      await this.cleanupOldFileOperations();

      structuredLogger.info('审计数据清理任务完成');
    } catch (error) {
      structuredLogger.error('审计数据清理任务失败', error);
    }
  }

  /**
   * 清理过期用户会话
   */
  async cleanupExpiredSessions() {
    const cutoffDate = new Date(Date.now() - (AUDIT_CONFIG.RETENTION_PERIODS.USER_SESSIONS * 24 * 60 * 60 * 1000));

    await db.execute(`
      DELETE FROM user_sessions
      WHERE login_time < ? AND session_status IN ('expired', 'terminated')
    `, [cutoffDate.toISOString()]);
  }

  /**
   * 清理过期数据导出
   */
  async cleanupExpiredExports() {
    await db.execute(`
      UPDATE data_export_audit
      SET deleted_at = CURRENT_TIMESTAMP
      WHERE auto_delete = 1
        AND created_at < datetime('now', '-' || delete_after_days || ' days')
        AND deleted_at IS NULL
    `);
  }

  /**
   * 清理旧文件操作记录
   */
  async cleanupOldFileOperations() {
    const cutoffDate = new Date(Date.now() - (AUDIT_CONFIG.RETENTION_PERIODS.FILE_OPERATIONS * 24 * 60 * 60 * 1000));

    await db.execute(`
      DELETE FROM file_operation_audit
      WHERE created_at < ? AND retention_required = 0
    `, [cutoffDate.toISOString()]);
  }

  /**
   * 获取审计统计
   */
  async getAuditStatistics(timeRange = '24h') {
    try {
      const timeMap = {
        '1h': "datetime('now', '-1 hour')",
        '24h': "datetime('now', '-1 day')",
        '7d': "datetime('now', '-7 days')",
        '30d': "datetime('now', '-30 days')",
        '90d': "datetime('now', '-90 days')"
      };

      const timeFilter = timeMap[timeRange] || timeMap['24h'];

      const [summary, recentViolations, recentExports] = await Promise.all([
        db.execute(`
          SELECT
            COUNT(*) as total_logs,
            COUNT(CASE WHEN level = 'audit' THEN 1 END) as audit_logs,
            COUNT(CASE WHEN level = 'security' THEN 1 END) as security_logs,
            COUNT(CASE WHEN level = 'compliance' THEN 1 END) as compliance_logs,
            COUNT(DISTINCT user_id) as active_users
          FROM audit_logs
          WHERE timestamp > ${timeFilter}
        `),

        db.execute(`
          SELECT violation_type, severity, COUNT(*) as count
          FROM compliance_violations
          WHERE timestamp > ${timeFilter}
          GROUP BY violation_type, severity
          ORDER BY count DESC
          LIMIT 10
        `),

        db.execute(`
          SELECT export_type, COUNT(*) as count, SUM(file_size_bytes) as total_size
          FROM data_export_audit
          WHERE timestamp > ${timeFilter}
          GROUP BY export_type
        `)
      ]);

      return {
        summary: summary.rows[0] || {},
        recentViolations: recentViolations.rows,
        recentExports: recentExports.rows,
        timeRange
      };
    } catch (error) {
      structuredLogger.error('获取审计统计失败', error);
      throw error;
    }
  }

  /**
   * 停止审计服务
   */
  stop() {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
      this.cleanupInterval = null;
      structuredLogger.info('审计服务已停止');
    }
  }
}

// 创建全局审计服务实例
const auditService = new AuditService();

export default auditService;
export { AUDIT_CONFIG };